package cn.kgc.springcloud2038.payment8001.service.impl;

import cn.kgc.springcloud2038.api.pojo.Payment;
import cn.kgc.springcloud2038.payment8001.mapper.PaymentDao;
import cn.kgc.springcloud2038.payment8001.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Resource
    private PaymentDao paymentDao;


    @Override
    public int create(Payment payment)
    {
        return paymentDao.create(payment);
    }

    @Override
    public Payment getPaymentById(Long id)
    {
        return paymentDao.getPaymentById(id);
    }

    //当10秒钟内，10次请求的错误比例达到60%，会出现熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            //启动熔断器
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            //请求数量
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            //统计时间
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            //错误百分比
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
    })
    @Override
    public String paymentCircuitBreaker(Integer id) {
        if(id<0){
            throw new RuntimeException("******id 不能负数");
        }
        return "success";
    }

    @Override
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
    {
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~   id: " +id;
    }
}
